package org.goyo.main.domain.dao.sale.impl;

import java.math.BigDecimal;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.goyo.common.exception.DBException;
import org.goyo.common.utils.Pager;
import org.goyo.common.utils.ToolUtils;
import org.goyo.main.domain.dao.BaseDAO;
import org.goyo.main.domain.dao.sale.IDispatchDao;
import org.goyo.main.domain.entity.sale.DispatchEntry;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;
@Repository
public class DispatchDaoImpl extends BaseDAO implements IDispatchDao{

	@Override
	public Pager findByCond(String cond, Pager pager,Object[] groupUuids) throws DBException {
		StringBuffer buf = new StringBuffer("from Dispatch where 1=1 ");
		
		buf.append(" and depGroup in ");
		buf.append(ToolUtils.getInParamter(groupUuids));
		if (StringUtils.isNotBlank(cond)) {
		  buf.append(" and ");
          buf.append(cond);
		}
	    String hql = this.addSort(buf, pager);
	    String countHql = "select count(*) "+buf.toString();
		return this.findObjectsByPager(hql,countHql, pager);
	}

	@Override
	public List<DispatchEntry> findByParentId(String parentId) throws DBException {
		String hql = "from DispatchEntry where parentId=?";
		return this.findObjects(hql, null, new Object[]{parentId});
	}

	@Override
	public void updateByUuidLoss(String uuid, double lossQty, BigDecimal lossAmount)
			throws DBException {
		String hql = "update DispatchEntry set lossQty=?,lossAmount=? where uuid=?";
		this.updateByHql(hql, new Object[]{lossQty,lossAmount,uuid});
	}

	@Override
	public void updateByUuidSignIn(String uuid, double signInQty)
			throws DBException {
		String hql = "update DispatchEntry set signInQty=? where uuid=?";
		this.updateByHql(hql, new Object[]{signInQty,uuid});		
	}
	
	@Override
	public Pager findByEntryCond(String cond, Pager pager) throws DBException {
		
		StringBuffer buf = new StringBuffer("from DispatchEntry where 1=1 ");
		if (StringUtils.isNotBlank(cond)) {
		  buf.append(" and ");
          buf.append(cond);
		}
	    String hql = this.addSort(buf, pager);
	    String countHql = "select count(*) "+buf.toString();
		return this.findObjectsByPager(hql,countHql, pager);
	}

	@Override
	public void updateSumOutQtyByUUid(String uuid) throws DBException {
		StringBuffer sql = new StringBuffer("update t_dispatch_entry set sum_out_qty = ");
		sql.append("(SELECT SUM(out_storage_qty) FROM t_sale_out_storage_entry where dispatchEntryId =?)");
		sql.append(" where uuid=? ");
		SQLQuery query = this.getSession().createSQLQuery(sql.toString());
		query.setParameter(0, uuid);
		query.setParameter(1, uuid);
		query.executeUpdate();
//		this.updateByHql(sql.toString(), new Object[]{uuid,uuid});		
	}

}
